/*
 *    Copyright (c) 2018-2025, sloth All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: sloth
 */

package cn.s1995.sloth.admin.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.s1995.sloth.admin.api.dto.ProcessFileDTO;
import cn.s1995.sloth.admin.api.dto.SysFileGroupDTO;
import cn.s1995.sloth.admin.api.entity.SysFile;
import cn.s1995.sloth.admin.api.entity.SysFileGroup;
import cn.s1995.sloth.admin.api.vo.FileUploadVO;
import cn.s1995.sloth.admin.service.SysFileService;
import cn.s1995.sloth.common.core.util.FileUtils;
import cn.s1995.sloth.common.core.util.R;
import cn.s1995.sloth.common.log.annotation.SysLog;
import cn.s1995.sloth.common.security.annotation.Inner;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

/**
 * 文件管理
 *
 * @author Luckly
 * @date 2019-06-18 17:18:42
 */
@RestController
@AllArgsConstructor
@RequestMapping("/sys-file")
@Tag(description = "sys-file", name = "UPMS-文件管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class SysFileController {

	private final SysFileService sysFileService;

	/**
	 * 分页查询
	 * @param page 分页对象
	 * @param sysFile 文件管理
	 * @return
	 */
	@Operation(summary = "分页查询", description = "分页查询")
	@GetMapping("/page")
	public R getSysFilePage(@ParameterObject Page page, @ParameterObject SysFile sysFile) {
		LambdaQueryWrapper<SysFile> wrapper = Wrappers.<SysFile>lambdaQuery()
				.eq(StrUtil.isNotBlank(sysFile.getType()), SysFile::getType, sysFile.getType())
				.eq(Objects.nonNull(sysFile.getGroupId()), SysFile::getGroupId, sysFile.getGroupId())
				.like(StrUtil.isNotBlank(sysFile.getOriginal()), SysFile::getOriginal, sysFile.getOriginal());
		return R.ok(sysFileService.page(page, wrapper));
	}

	/**
	 * 通过id删除文件
	 * @param ids id 列表
	 * @return R
	 */
	@Operation(summary = "通过id删除文件", description = "通过id删除文件")
	@SysLog("删除文件")
	@DeleteMapping
	@PreAuthorize("@pms.hasPermission('sys_file_del')")
	public R removeById(@RequestBody Long[] ids) {
		for (Long id : ids) {
			sysFileService.deleteFile(id);
		}
		return R.ok();
	}

	/**
	 * 通过文件名删除文件
	 * @param fileNameList 文件名列表
	 * @return R
	 */
	@Operation(summary = "通过文件名删除文件", description = "通过文件名删除文件")
	@SysLog("删除文件")
	@DeleteMapping("/fileName")
	@PreAuthorize("@pms.hasPermission('sys_file_del')")
	public R removeByFileName(@RequestBody List<String> fileNameList) {
		for (String fileName : fileNameList) {
			sysFileService.deleteFile(fileName);
		}
		return R.ok();
	}

	@PutMapping("/rename")
	public R rename(@RequestBody SysFile sysFile) {
		return R.ok(sysFileService.updateById(sysFile));
	}

	/**
	 * 上传文件 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常
	 * @param file 资源
	 * @param dir 文件夹
	 * @param groupId 分组id
	// * @param type 类型：10-图片 20-视频 30-文件
	 * @return R(/ admin / bucketName / filename)
	 */
	@PostMapping(value = "/upload")
	@Operation(
			summary = "文件上传",
			description = "文件上传：<br/>" +
					"图片上传：默认情况下根据对应图片上传限制参数判断，如果超出则对图片进行压缩thumbnailFileName参数返回压缩后的图片并以”_thumb“结尾， 如：压缩图为 a.png -> a_thumb.png <br/>" +
					"		如果是产品图片则prodThumbnail参数返回多个压缩尺寸的图片，fileName返回原图<br/>"
	)
	@Parameters({
			// @Parameter(name = "file", description = "文件", required = true),
			@Parameter(name = "dir", description = "文件夹", required = false, example = "2024-01-01"),
			@Parameter(name = "groupId", description = "分组id", required = false, example = ""),
			// @Parameter(name = "type", description = "类型：10-图片 20-视频 30-文件", required = false, example = "10"),
			@Parameter(name = "isHandlePicCompression", description = "是否处理图片压缩", required = false, example = "true"),
			@Parameter(name = "isHandleVideoFrame", description = "是否处理视频帧", required = false, example = "true"),
			@Parameter(name = "videoFrameParamValue", description = "视频帧参数值，详见 https://help.aliyun.com/zh/oss/user-guide/video-snapshots?spm=a2c4g.11186623.0.i3", required = false, example = "video/snapshot,t_3000,f_jpg,w_0,h_0,m_fast"),
	})
	public R<FileUploadVO> upload(@RequestPart MultipartFile file,
								  @RequestParam(required = false) String dir,
								  @RequestParam(required = false) Long groupId,
								  // @RequestParam(required = false) String type,
								  @RequestParam(required = false) Boolean isHandlePicCompression,
								  @RequestParam(required = false) Boolean isHandleVideoFrame,
								  @RequestParam(required = false) String videoFrameParamValue) {
		String type;
		String extName = FileUtil.extName(file.getOriginalFilename());
		if (FileUtils.isImage(extName)) {
			type = "10";
		} else if (FileUtils.isVideo(extName)) {
			type = "20";
		} else {
			type = "30";
		}
		// 默认处理图片压缩
		if (Objects.isNull(isHandlePicCompression)) {
			isHandlePicCompression = Boolean.TRUE;
		}

		if (StrUtil.isEmpty(dir)) {
			// 没有传入目录默认当前日期作为目录
			dir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		}

		return sysFileService.uploadFile(file, dir, groupId, type, isHandlePicCompression, isHandleVideoFrame, videoFrameParamValue);
	}

	/**
	 * 获取文件
	 * @param fileName 文件空间/名称
	 * @param response
	 * @return
	 */
	@Inner(false)
	@GetMapping("/oss/file")
	public void file(String fileName, HttpServletResponse response) {
		sysFileService.getFile(fileName, response);
	}

	/**
	 * 获取本地（resources）文件
	 * @param fileName 文件名称
	 * @param response 本地文件
	 */
	@SneakyThrows
	@GetMapping("/local/file/{fileName}")
	public void localFile(@PathVariable String fileName, HttpServletResponse response) {
		ClassPathResource resource = new ClassPathResource("file/" + fileName);
		response.setContentType("application/octet-stream; charset=UTF-8");
		IoUtil.copy(resource.getInputStream(), response.getOutputStream());
	}

	/**
	 * 查询文件组列表
	 * @param fileGroup SysFileGroup对象，用于筛选条件
	 * @return 包含文件组列表的R对象
	 */
	@GetMapping("/group/list")
	public R listGroup(SysFileGroup fileGroup) {
		return R.ok(sysFileService.listFileGroup(fileGroup));
	}

	/**
	 * 添加文件组
	 * @param fileGroup SysFileGroup对象，要添加的文件组信息
	 * @return 包含添加结果的R对象
	 */
	@PostMapping("/group/add")
	public R addGroup(@RequestBody SysFileGroup fileGroup) {
		return R.ok(sysFileService.saveOrUpdateGroup(fileGroup));
	}

	/**
	 * 更新文件组
	 * @param fileGroup SysFileGroup对象，要更新的文件组信息
	 * @return 包含更新结果的R对象
	 */
	@PutMapping("/group/update")
	public R updateGroup(@RequestBody SysFileGroup fileGroup) {
		return R.ok(sysFileService.saveOrUpdateGroup(fileGroup));
	}

	/**
	 * 删除文件组
	 * @param id 待删除文件组的ID
	 * @return 包含删除结果的R对象
	 */
	@DeleteMapping("/group/delete/{id}")
	public R updateGroup(@PathVariable Long id) {
		return R.ok(sysFileService.deleteGroup(id));
	}

	/**
	 * 移动文件组
	 * @param fileGroupDTO SysFileGroupDTO对象，要移动的文件组信息
	 * @return 包含移动结果的R对象
	 */
	@PutMapping("/group/move")
	public R moveFileGroup(@RequestBody SysFileGroupDTO fileGroupDTO) {
		return R.ok(sysFileService.moveFileGroup(fileGroupDTO));
	}

	@Parameters({
			@Parameter(name = "dir", description = "文件夹", required = false, example = "2024-01-01"),
			@Parameter(name = "fileName", description = "文件名", required = true, example = "a.mp4"),
	})
	@GetMapping("/url")
	@Inner
	public R<URL> getUrl(@RequestParam(required = false) String dir, @RequestParam String fileName) {
		return R.ok(sysFileService.getUrl(dir, fileName));
	}

	@Inner
	@PostMapping("/extract-frame")
	public R extractFrame(ProcessFileDTO dto) {
		sysFileService.extractFrame(dto);
		return R.ok();
	}

	@Inner
	@PostMapping("/extract-frame-alioss")
	public R extractFrameForAliOss(@RequestBody ProcessFileDTO dto) {
		sysFileService.extractFrameForAliOss(dto);
		return R.ok();
	}

}
